<!--
 * @Author: your name
 * @Date: 2021-04-08 22:54:51
 * @LastEditTime: 2021-04-08 23:15:09
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \JavaScript\06 - 双向数据绑定.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <span id="spanName"></span>
  <br />
  <input id="inptName" type="text">
  <script>
    // ES5
    let obj = {
      name: ''
    }
    let newObj = JSON.parse(JSON.stringify(obj))
    Object.defineProperty(obj, 'name', {
      get() {
        return newObj.name
      },
      set(val) {
        newObj.name = val
        observer()
      }
    })
    function observer() {
      spanName.innerHTML = newObj.name
      inptName.value = newObj.name
    }
    setTimeout(() => {
      obj.name = 'Hello World'
    }, 1000);
    inptName.oninput = function() {
      obj.name = this.value
    }
  </script>

  <script>
    // ES6
    let obj1 = {
      name: ''
    }
    obj1 = new Proxy(obj1, {
      get: (target, prop) => {
        return target[prop]
      },
      set: (target, prop, val) => {
        target[prop] = val
        observer()
      }
    })
    function observer() {
      spanName.innerHTML = obj1.name
      inptName.value = obj1.name
    }
    inptName.oninput = function() {
      obj1.name = this.value
    }
    setTimeout(() => {
      obj1.name = 'aaa'
    }, 1000);
  </script>
</body>
</html>